import { UserConfigExport, loadEnv, ConfigEnv } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import { ExpandImportMetaEnv, MergeUnion } from './src/utils/type'

export default (param: ConfigEnv) => {
  const { mode } = param
  const env = loadEnv(mode, process.cwd()) as unknown as ExpandImportMetaEnv
  const isSliceBaseUrl = JSON.parse(env.VITE_SLICE_REQUEST_BASE_URL)
  const getConfig = <T extends UserConfigExport>(
    c: T): MergeUnion.MergeOption<T & UserConfigExport> => c as any
  const config = getConfig({
    plugins: [
      uni()
    ],
    server: {
      port: 5173,
      proxy: {
        [env.VITE_REQUEST_BASE_URL]: {
          target: env.VITE_REQUEST_URL,
          changeOrigin: true,
          ws: true,
          rewrite(reqUrl){
            const reg = new RegExp('^' + env.VITE_REQUEST_BASE_URL)
            const url = isSliceBaseUrl ? reqUrl.replace(reg, '') : reqUrl
            return url
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          // additionalData: [
          //   'variable',
          //   'mixin',
          //   'function'
          // ].map(item => `@use "@/styles/${item}.scss" as *;`).join('\n')
        }
      }
    },
    build: {}
  })

  if (env.VITE_OUT_DIR) {
    config.base = '/' + env.VITE_OUT_DIR + '/'
    config.build.outDir = env.VITE_OUT_DIR
  }

  return config
}